package com.ita.servlet.merchant;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.jms.JMSException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ita.factory.MServiceFactory;
import com.ita.pojo.Merchant;
import com.ita.service.MerchantService;
import com.ita.util.Base64Util;
import com.ita.util.Constant;
import com.ita.util.FileUtil;
import com.ita.util.PropertiesUtil;

@WebServlet("/sec/update")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private MerchantService mService;
	private ServletFileUpload upload;
	private Properties prop;

	// private static InputStream sin;

	public UpdateServlet() throws JMSException {
		prop = PropertiesUtil.getProp();
		mService = MServiceFactory.getMerchantService();
		DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
				new File("/temp"));
		upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String idcardPath = prop.getProperty("IDCARD_PATH");
		String imgPath = prop.getProperty("IMG_PATH");
		boolean isError = false;
		String msg = "";
		HttpSession session = request.getSession();
		Merchant m = (Merchant) session.getAttribute("m");
		String name = m.getName();

		String server_path = "http://"
				+ InetAddress.getLocalHost().getHostAddress() + ":" + "9000/";

		String pathName = null;
		String card_path = null;
		String img_path = null;

		List<FileItem> items = null;

		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		String oldPwd = items.get(0).getString("utf-8");
		System.out.println(oldPwd);
		String newPwd = items.get(1).getString("utf-8");
		System.out.println(newPwd);
		String confirmPwd = items.get(2).getString("utf-8");
		System.out.println(confirmPwd);

		if (!mService.checkPassword(name, oldPwd)) {
//			msg = "old password not true";
//			response.sendRedirect("update.jsp");
			request.setAttribute("err_msg", "old password not true");
			request.getRequestDispatcher("update.jsp")
					.forward(request, response);
			return;
		}

		if (!newPwd.equals(confirmPwd)) {
//			msg = "new password should be the same";
//			response.sendRedirect("update.jsp");
//			return;
			
			request.setAttribute("err_msg", "new password should be the same");
			request.getRequestDispatcher("update.jsp")
					.forward(request, response);
			return;
		}

		if (oldPwd.equals("") || newPwd.equals("") || confirmPwd.equals("")) {
//			msg = "All null";
//			response.sendRedirect("update.jsp");
//			return;
			request.setAttribute("err_msg", "All null");
			request.getRequestDispatcher("update.jsp")
					.forward(request, response);
			return;
			
		}

	
		for (FileItem item : items) {
			String field = item.getFieldName();
			String value = item.getString("utf-8");
			if (item.isFormField()) {
				switch (field) {
				case "newpwd2":
					m.setPassword(value);
					break;
				case "storename":
					m.setStoreName(value);
					break;
				case "addr":
					m.setAddress(value);
					break;
				}
			} else {
				String base64 = "";
				InputStream in = null;
				try {
					in = item.getInputStream();
					if (in.available() < (1024 * 1024)) {
						String image_type = item
								.getName()
								.subSequence(item.getName().lastIndexOf("."),
										item.getName().length()).toString();
						if (".jpg".equals(image_type)
								|| ".gif".equals(image_type)
								|| ".jpeg".equals(image_type)
								|| ".png".equals(image_type)) {

							byte[] bytes = new byte[in.available()];
							in.read(bytes);
							base64 = Base64Util.byteToBase64(bytes);

							switch (field) {
							case "idcard":
								m.setIdcard(base64);
								pathName = idcardPath + m.getId() + image_type;
								card_path = "/idcard/" + m.getId() + image_type;
								break;
							case "img":
								m.setImg(base64);
								pathName = imgPath + m.getId() + image_type;
								img_path = "/img/" + m.getId() + image_type;
								break;
							}
							FileUtil.writeFile(pathName, bytes);
						} else {
							isError = true;
							msg = "Image format error";
						}
					} else {
						isError = true;
						msg = "Size out of 1024KB";
					}
				} catch (Exception e) {
					isError = true;
					msg = "Not choose your file";
				}

			}
		}

		if (isError) {
			request.setAttribute("err_msg", msg);
//			request.getRequestDispatcher("update").forward(request, response);
			request.getRequestDispatcher("update.jsp")
					.forward(request, response);
			
			return;
		}

		System.out.println(m);

		m.setSubTime(new Date().getTime());
		mService.sendToMQ(m);

		m.setIdcard(server_path + card_path);
		m.setImg(server_path + img_path);
		mService.updateMerchant(m);
//		session.removeAttribute("m");
		session.setAttribute("m", m);
//		response.sendRedirect("info.jsp");
		response.sendRedirect("../info");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}
